﻿	$('head').append('<link rel="stylesheet" href="http://code.jquery.com/ui/1.8.20/themes/base/jquery-ui.css" type="text/css" />');
	$('head').append('<link rel="stylesheet" href="http://ftvi.googlecode.com/git/cannes2012/cannes-min.css" type="text/css" />');
	var politique = [
						'Amour',
						'Cosmopolis',
						'De rouille et d\'os',
						'Au-delà des collines',
						'Holy Motors',
						'Cogan - La mort en douce',
						'Lawless',
						'Like someone in love',
						'Moonrise kingdom',
						'Sur la route',
						'La part des anges',
						'Paperboy',
						'Vous n\'avez encore rien vu',
						'La chasse',
						'In another country',
						'Emmanuelle Riva',
						'Isabelle Huppert',
						'Marion Cotillard',
						'Edith Scob',
						'Eva Mendes',
						'Jessica Chastain', 
						'Frances McDormand',
						'Reese Witherspoon',
						'Kristen Stewart',
						'Jasmin Riggins',
						'Nicole Kidman',
						'Sabine Azéma',
						'J.-L. Trintignant',
						'Matthias Schoenaerts',
						'Robert Pattinson',
						'Denis Lavant',
						'Brad Pitt',
						'Shia Labeouf',
						'Bruce Willis',
						'Mads Mikkelsen',
						'Matthew McConaughey',
						'Garrett Hedlund',
						'Paul Brannigan',
						'Pierre Arditi'
					];
						
	var ministeres = [
						'Palme d\'or',
						'Grand Prix',
						'Prix de la mise en scène',
						'Prix du scénario',
						'Prix du jury',
						'Prix d\'interprétation féminine',
						'Prix d\'interprétation masculine'					
					];
					
	function urlFriendly(str) {
		return str
		.toLowerCase()
		.replace(/^\s+|\s+$/g, "")
		.replace(/[_|\s]+/g, "-")
		.replace(/[^a-z0-9-]+/g, "")
		.replace(/[-]+/g, "-")
		.replace(/^-+|-+$/g, "");
	}
	
	function check() {
		var ok = true;
		if ($('.dropzone3').children('ul').children('li').size() == 0) { ok = false; }
		$('.dropzone').each(function() {
			if ($(this).children('ul').children('li').size() == 0) {
				ok = false;
			}
		});
		return ok;
	}
	
	function saveValeur() {
		$('#str_share').attr('value', '');
		$('.ui-droppable').each(function() {
			var div_id = $(this).attr('id');
			for (var cpt = 0 ; cpt < ministeres.length ; cpt ++) {
				if (('dropzone_' + urlFriendly(ministeres[cpt])) == div_id) {
					if ($(this).children('ul').children('li').size() != 0) {
						$('#str_share').attr('value', $('#str_share').attr('value') + '-' + $(this).children('ul').children('li').attr('id'));
					}
				}	
			}
		});
		if ($('#str_share').attr('value').substr(0, 1) == '-') {
			$('#str_share').attr('value', $('#str_share').attr('value').substr(1, $('#str_share').attr('value').length - 1));
		}
	}
	
	function shareFacebook() {
		if (check()) {
			// Enregistrement de la valeur
			saveValeur();
			// Popup de partage
			var width = 650;
			var height = 430;
			var pos_x = 0;
			var pos_y = 0;
			var options = '';
			pos_x = ($(window).width() - width) / 2;
			pos_y = ($(window).height() - height) / 2;
			options = 'width=' + width + ',height=' + height + ',top=' + pos_y + ',left=' + pos_x + ',location=no,resizable=yes,status=no,titlebar=no,toolbar=no';
			var url_page = window.location.href;
			if (url_page.substr(url_page.length - 1, 1) == '#') {			
				url_page = url_page.substr(0, url_page.length - 1);
			}
			
			url_page += '#' + $('#str_share').attr('value');
			var url = 'https://www.facebook.com/sharer.php?u=' + encodeURIComponent(url_page) + '&t=' + encodeURIComponent('toi aussi, fait ton gouvernement');
			window.open(url, 'partage_facebook', options);
		} else {
			alert('Votre palmarès n\'est pas complet.');
		}
	}
	
	function shareTwitter() {
		if (check()) {
			// Enregistrement de la valeur
			saveValeur();			
			// Popup de partage
			var width = 650;
			var height = 430;
			var pos_x = 0;
			var pos_y = 0;
			var options = '';
			pos_x = ($(window).width() - width) / 2;
			pos_y = ($(window).height() - height) / 2;
			options = 'width=' + width + ',height=' + height + ',top=' + pos_y + ',left=' + pos_x + ',location=no,resizable=yes,status=no,titlebar=no,toolbar=no';
			var title = 'Coucou, tu veux voir mon gouvernement ?';
			var url_page = window.location.href;
			if (url_page.substr(url_page.length - 1, 1) == '#') {			
				url_page = url_page.substr(0, url_page.length - 1);
			}
			url_page += '#' + $('#str_share').attr('value');
			var url = 'http://twitter.com/share?related=francetvinfo&via=francetvinfo&lang=fr&text=' + encodeURIComponent(title) + '&url=' + encodeURIComponent(url_page);
			window.open(url, 'partage_twitter', options);
		} else {
			alert('Votre palmarès n\'est pas complet.');
		}
	}
	
	function raz() {
		window.location.hash = '';
		window.location.href = window.location.href;
		window.location.reload();
	}
	
	function generateIhm() {
		var code_html = '';
		
		/**
		 ** Génération des container
		 **/
		code_html += '<input type="hidden" id="str_share" value="" />';
		code_html += '<div class="demo ui-widget ui-helper-clearfix">';
		code_html += '    <ul id="gallery" class="gallery ui-helper-reset ui-helper-clearfix"></ul>';
		code_html += '    <div id="container"></div>';
		code_html += '</div>';
		$(code_html).appendTo($('#fais_ton_cannes'));
		
		/**
		 ** Génération des candidats
		 **/
		code_html = '';
		for (var cpt = 0 ; cpt < politique.length ; cpt ++) {
			if ((cpt == 15) || (cpt == 27)) {
				code_html += '<li style="clear:both;width:509px; height:4px;background-color:#AA8905;padding:0; margin: 2px 0 5px;"></li>';
			}
			code_html += '<li id="' + cpt + '" class="ui-widget-content ui-corner-tr rang' + cpt + '">';
			code_html += '    <h5 class="ui-widget-header">' + politique[cpt] + '</h5>';
			code_html += '    <img src="http://ftvi.googlecode.com/git/cannes2012/' + urlFriendly(politique[cpt]) + '.jpg"  alt="' + politique[cpt] + '" width="70" height="70" />';
			code_html += '</li>';
		}
		$(code_html).appendTo($('#gallery'));
		
		/**
		 ** Génération des minitères
		 **/
		code_html = '';
		for (cpt = 0 ; cpt < ministeres.length ; cpt ++) {
			if (!cpt) {
				code_html += '<div id="premier_ministre">';
				code_html += '    <div id="dropzone_' + urlFriendly(ministeres[cpt]) + '" class="dropzone3">';
				code_html += '        <h4 class="ui-widget-header">' + ministeres[cpt] + '</h4>';
				code_html += '    </div>';
				code_html += '</div>';
			} else {
				code_html += '<div id="dropzone_' + urlFriendly(ministeres[cpt]) + '" class="dropzone">';
				code_html += '   <h4 class="ui-widget-header">' + ministeres[cpt] + '</h4>';
				code_html += '</div>';
			}
		}
		$(code_html).appendTo($('#container'));
		
		/**
		 ** Bouton de partage
		 **/
		code_html = '';
		code_html += '<div style="clear: both;"></div>';
		code_html += '<div class="share">';
		code_html += '   <img src="http://ftvi.googlecode.com/files/share_facebook.jpg" id="share_facebook" />';
		code_html += '   <img src="http://ftvi.googlecode.com/files/share_twitter.jpg" id="share_twitter" />';
		code_html += '   <img src="http://ftvi.googlecode.com/files/zero.jpg" id="raz" />';
		code_html += '</div>';
		$(code_html).appendTo($('#container'));
		
		$('#share_facebook').click(function() {	shareFacebook(); });
		$('#share_twitter').click(function() { shareTwitter(); });
		$('#raz').click(function() { raz(); });
		
		$('<div style="clear:both;"></div>').appendTo($('.demo'));
	}
			
	/** Execution au démarrage **/
	$(function() {
		/**
		 ** On génère la grille de politiques et ministères
		 **/
		generateIhm();
		
		/**
		 ** On est sur une visualisaiton
		 **/
		var hash = (window.location.hash.substring(1)).split('&');
        if (hash != '') {
			hash = ('' + hash).split('-');			
			for (cpt = 0 ; cpt < ministeres.length ; cpt ++) {
				deposeImage($('#dropzone_' + urlFriendly(ministeres[cpt])), $('#' + hash[cpt]));
			}
			// On centre le résultat
			$('#gallery').remove();
			$('#container').css('float', 'none');
			$('#container').css('margin', '0 auto');
			$('#container').css('backgroundColor', '#fff');
			
			// Affiche btn "A toi de jouer"
			$('.share').remove();
			var code_html = '';
			code_html += '<div class="share">';
			code_html += '   <img src="http://ftvi.googlecode.com/files/compoz.jpg" id="composer" />';
			code_html += '</div>';
			$(code_html).appendTo($('#container'));
			$('#composer').click(function() { raz(); });
		}
		
		/**
		 ** Drag & Drop
		 **/
		var $gallery = $("#gallery");

		$( "li", $gallery ).draggable({
			cancel: "a.ui-icon", 
			revert: "invalid", 
			containment: $( "#demo-frame" ).length ? "#demo-frame" : "document", 
			helper: "clone",
			cursor: "move"
		});
		
		$('.dropzone3').droppable({
			accept: "#gallery > li",
			activeClass: "ui-state-highlight",
			drop: function( event, ui ) {
				var idx_cont = 0;
				for (cpt = 0 ; cpt < ministeres.length ; cpt ++) {
					if ($(this).attr('id') == 'dropzone_' + urlFriendly(ministeres[cpt])) {
						idx_cont = cpt;
					}
				}
				if ((idx_cont <= 4) && ((ui.draggable).attr('id') > 14) ) {
					// Film
					alert('Vous ne pouvez attribuer ce prix qu\'à des films.');
				} else {
					deposeImage($(this), ui.draggable);
				}
			}
		});		
		
		$('.dropzone').each(function() {
		   $(this).droppable({
				accept: "#gallery > li",
				activeClass: "ui-state-highlight",
				drop: function( event, ui ) {
					var idx_cont = 0;
					for (cpt = 0 ; cpt < ministeres.length ; cpt ++) {
						if ($(this).attr('id') == 'dropzone_' + urlFriendly(ministeres[cpt])) {
							idx_cont = cpt;
						}
					}
					if ((idx_cont <= 4) && ((ui.draggable).attr('id') > 14) ) {
						// Film
						alert('Vous ne pouvez attribuer ce prix qu\'à des films.');
					} else {
						//alert(idx_cont + ' - ' + (ui.draggable).attr('id'));
						if ((idx_cont == 5) && (((ui.draggable).attr('id') < 15) || ((ui.draggable).attr('id') > 26))) {
							alert('Vous ne pouvez attribuer ce prix qu\'à des actrices.');
						} else {
							if ((idx_cont == 6) && ((ui.draggable).attr('id') < 27)) {
								alert('Vous ne pouvez attribuer ce prix qu\'à des acteurs.');
							} else {
								deposeImage($(this), ui.draggable);
							}
						}
					}
				}
			});
		});
			
		$gallery.droppable({
			accept: "#container li",
			activeClass: "custom-state-active",
			drop: function( event, ui ) {
				retireImage(ui.draggable );
			}
		});
		
		var recycle_icon = "";
		function deposeImage($node, $item) {
			if ($node.children('ul').children('li').size() != 0) {
				$node.children('ul').children('li').appendTo($gallery);
				$node.children('ul').children().remove();
			}
			$item.fadeOut(function() {
				var $list = $( "ul",  $node).length ?
					$( "ul", $node ) :
					$( "<ul class='gallery ui-helper-reset'/>" ).appendTo( $node );
				$item.find( "a.ui-icon-trash" ).remove();
				$item.append( recycle_icon ).appendTo( $list ).fadeIn(function() {
				});
			});
		}

		var trash_icon = "";
		function retireImage($item) {
			$item.fadeOut(function() {
				$item
					.find( "a.ui-icon-refresh" )
						.remove()
					.end()
					.css( "width", "70px")
					.append( trash_icon )
					.find( "img" )
						.css( "height", "70px" )
					.end()
					.appendTo( $gallery )
					.fadeIn();
			});
		}
	});